/**
 *
 * HTML5 Image uploader with Jcrop
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 * 
 * Copyright 2012, Script Tutorials
 * http://www.script-tutorials.com/
 */

// convert bytes into friendly format
function bytesToSize(bytes) {
    var sizes = ['Bytes', 'KB', 'MB'];
    if (bytes == 0) return 'n/a';
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};

/*@param: imageId 图片文件元素结点的id */
function fileSelectHandler(imageObj) {

    // get selected file
    var oFile = $(imageObj)[0].files[0];

    // hide all errors
    $('.error').hide();

    // check for image type (jpg and png are allowed)
    var rFilter = /^(image\/jpeg|image\/png|image\/gif)$/i;
    if (! rFilter.test(oFile.type)) {
        createPNotify("导入提示", "error", "请添加正确的文件类型 jpg,png,gif");
        $('#submit').attr("disabled","disabled");
        $(imageObj).val("");

        if($('#submit_button') != null){
            $('#submit_button').attr("disabled","disabled");
        }

        return;
    }

    // check for file size
    if (oFile.size > 1000 * 1024) {
        createPNotify("导入提示", "error", "文件大小不得超过1M");
        $('#submit').attr("disabled","disabled");
        $(imageObj).val("");

        if($('#submit_button') != null){
            $('#submit_button').attr("disabled","disabled");
        }

        return;
    }

    $('#submit').removeAttr("disabled");
    if($('#submit_button') != null){
        $('#submit_button').removeAttr("disabled");
    }

    // preview element
    var oImage = document.getElementById('preview');

    // prepare HTML5 FileReader
    var oReader = new FileReader();
        oReader.onload = function(e) {

        // e.target.result contains the DataURL which we can use as a source of the image
        oImage.src = e.target.result;
        oImage.onload = function () { // onload event handler

            // display step 2
            $('.step').fadeIn(500);

            // Create variables (in this scope) to hold the Jcrop API and image size
            var jcrop_api, boundx, boundy;

            // destroy Jcrop if it is existed
            if (typeof jcrop_api != 'undefined') 
                jcrop_api.destroy();

        };
    };

    // read selected file as DataURL
    oReader.readAsDataURL(oFile);
}